package com.ysweet.web.core.config;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl;
import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl;
import com.google.common.collect.Maps;
import com.ysweet.common.constant.SystemConfigConstants;
import com.ysweet.common.core.redis.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Map;


/**
 * @author <a href="https://github.com/binarywang">Binary Wang</a>
 */

@Configuration(proxyBeanMethods = false)
public class WxMaConfiguration {
	private static Map<String, WxMaServiceImpl> serviceMap = Maps.newHashMap();
	private static RedisCache redisCache;

	@Autowired
	public WxMaConfiguration(RedisCache redisCache) {
		WxMaConfiguration.redisCache = redisCache;
	}

	public static WxMaService getWxMaService() {
		String appId = redisCache.getCacheObject(SystemConfigConstants.WXAPP_APPID);
		WxMaServiceImpl wxMaService = serviceMap.get(appId);
		if (wxMaService == null) {
			WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl();
			config.setMsgDataFormat("JSON");
			config.setAppid(redisCache.getCacheObject(SystemConfigConstants.WXAPP_APPID));
			config.setSecret(redisCache.getCacheObject(SystemConfigConstants.WXAPP_SECRET));
			wxMaService = new WxMaServiceImpl();
			wxMaService.setWxMaConfig(config);
			serviceMap.put(appId, wxMaService);
		}
		return wxMaService;
	}

	/**
	 * 移除WxMpService
	 */
	public static void removeWxMaService(String appid) {
		serviceMap.remove(appid);
	}

}
